<script>
import { mapState } from 'vuex'
import DisheFlavorForm from '@/views/dishes/components/disheFlavorForm.vue'

export default {
  name: 'dishes',
  components: { DisheFlavorForm },
  data() {
    return {
      pageParams: {
        name: null,
        categoryId: null,
        status: null,
        page: 1,
        pageSize: 10
      },
      dishList: [],
      selectDishIds: [],
      drawer: false,
      edit: false,
      flavorFormRef: null
    }
  },
  methods: {
    /* 获取菜品分类的回调函数 */
    async fetchDishOrStemCategory() {
      try {
        this.dishList = await this.$store.dispatch('dishStore/fetchDishOrStemCategoryAction', 1)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 获取菜品列表的回调函数 */
    async fetchDishList() {
      try {
        await this.$store.dispatch('dishStore/fetchDishListAction', this.pageParams)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /*
    *分页参数
    *  */
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize
      this.fetchDishList()
    },

    handleCurrentChange(page) {
      this.pageParams.page = page
      this.fetchDishList()
    },

    /* 搜索按钮的回调函数 */
    handleSearch() {
      this.pageParams.page = 1
      this.fetchDishList()
    },

    /* 点击删除按钮的回调函数 */
    async handleDelete(row) {
      if (row.status === 1) return this.$message.warning(`${row.name}菜品正在售卖不能删除`)
      const confirm = await this.$confirm(`确定删除${row.name}吗?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).catch(error => error)
      if (confirm === 'cancel') return
      try {
        const message = await this.$store.dispatch('dishStore/deleteDishAction', row.id)
        await this.fetchDishList()
        this.$message.success(message)
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    /* 更新菜品状态的回调函数 */
    async updateStatus(status, id) {
      try {
        const newStatus = status === 1 ? 0 : 1
        const updateMessage = await this.$store.dispatch('dishStore/updateDishStatusAction', { status: newStatus, id })
        await this.fetchDishList()
        this.$message.success(updateMessage)
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    /* 新建菜品的回调函数 */
    handleAdd() {
      this.drawer = true
      this.edit = false
    },

    /* 修改菜品的回调函数 */
    handleEdit(row) {
      this.drawer = true
      this.edit = true
      this.$nextTick(() => {
        this.$refs.flavorFormRef.fetchDishDetail(row.id)
      })
    },

    // 子组件成功的自定义事件
    dishSuccess() {
      this.drawer = false
      this.fetchDishList()
    },

    // 表格的勾选事件
    handleSelectionChange(dishList) {
      this.selectDishIds = dishList.map(dish => dish.id)
    },

    // 批量删除菜品的回调函数
    async handleDeleteAll() {
      if (!this.selectDishIds.length) return
      try {
        const message = await this.$store.dispatch('dishStore/deleteDishAction', this.selectDishIds.join(','))
        this.fetchDishList()
        this.$message.success(message)
      } catch (error) {
        this.$message.error(error.message)
      }
    }

  },
  computed: {
    ...mapState('dishStore', ['records', 'total']),
    title() {
      return this.edit ? '编辑菜品' : '新建菜品'
    }
  },
  mounted() {
    this.fetchDishOrStemCategory()
    this.fetchDishList()
  }
}
</script>

<template>
  <div class="dishes-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row>
          <el-col :span="16">
            <el-form size="small" label-width="80px" inline :model="pageParams">
              <el-form-item label="菜品名称:">
                <el-input placeholder="请输入菜品名称" v-model="pageParams.name"></el-input>
              </el-form-item>
              <el-form-item label="菜品分类:">
                <el-select v-model="pageParams.categoryId">
                  <el-option :value="undefined" label="所有分类"></el-option>
                  <el-option v-for="(item) in dishList" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="售卖状态:">
                <el-select v-model="pageParams.status">
                  <el-option :value="undefined" label="所有"></el-option>
                  <el-option :value="1" label="起售"></el-option>
                  <el-option :value="0" label="停售"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-button size="small" type="info" icon="el-icon-search" @click="handleSearch">查询菜品</el-button>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDeleteAll">批量删除</el-button>
            <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd">新建菜品</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table size="small" border stripe :data="records" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="name" label="菜品名称" align="center"></el-table-column>
        <el-table-column prop="description" label="菜品描述" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="菜品图片" align="center">
          <template #default="{row}">
            <el-avatar :size="40" :src="row.image">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="菜品分类" align="center"></el-table-column>
        <el-table-column label="菜品售价" align="center">
          <template #default="{row}">
            ￥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column label="售卖状态" align="center">
          <template #default="{row}">
            <el-switch v-model="row.status" disabled :active-value="1" :inactive-value="0" active-text="起售" inactive-text="停售" active-color="#13ce66"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="操作时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="text" @click="handleEdit(row)">修改</el-button>
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
            <el-button type="text" @click="updateStatus(row.status,row.id)">{{ row.status === 1 ? '停售' : '起售' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParams.page" :page-sizes="[10, 20, 30, 40]" :page-size="pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background></el-pagination>
    </el-card>
    <el-drawer :title="title" :visible.sync="drawer" width="80%" @close="$refs.flavorFormRef.resetForm()">
      <dishe-flavor-form ref="flavorFormRef" :dish-list="dishList" :edit="edit" @success="dishSuccess"></dishe-flavor-form>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.dishes-container {
  padding: 25px;

  .el-table {
    margin-bottom: 10px;
  }

  .el-pagination {
    display: flex;
    justify-content: center;
  }

  ::v-deep .el-drawer {
    width: 40% !important;
  }
}
</style>
